package com.elitel.frame.main.config.serviceaccess.interceptor;

import com.elitel.frame.base.service.SysPrjServiceService;
import com.elitel.frame.core.util.ApplicationContextHelper;
import com.elitel.frame.main.config.serviceaccess.util.ServiceAccessPrintWriterUtil;
import com.elitel.frame.main.config.serviceaccess.util.ServiceAccessResponseStatus;
import com.elitel.frame.main.entity.SysPrjservice;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.elitel.common.core.constant.RequestConstant.SERVICE_ID;

/**
 * 服务状态拦截器
 * @author hi_bj
 * @since 2023-10-17
 */

public class ServiceStatusInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        SysPrjServiceService sysPrjServiceService = ApplicationContextHelper.getApplicationContext().getBean(SysPrjServiceService.class);
        SysPrjservice sysPrjservice = sysPrjServiceService.getSysPrjserviceByServiceCode(request.getParameter(SERVICE_ID));
        if (ObjectUtils.isEmpty(sysPrjservice)) {
            ServiceAccessPrintWriterUtil.write(response, ServiceAccessResponseStatus.SERVICE_NOT_FOUND.initValue());
            return false;
        }
        //服务状态为禁用
        if (sysPrjservice.getStatus() == 0) {
            ServiceAccessPrintWriterUtil.write(response,  ServiceAccessResponseStatus.SERVICE_NOT_AVAILABLE.initValue());
            return false;
        }
        return true;
    }
}
